<template>
	<view class="container">
		<uni-load-more v-if="loading" status="loading" iconType="circle"></uni-load-more>

		<uni-calendar :lunar="false" @change="handleDateChange" :date="currentDate" :selected="selectedDates || []"
			@monthSwitch="handleMonthSwitch" :showMonth="false"></uni-calendar>

		<view class="time-tabs">
			<view v-for="(time, idx) in timeTabs" :key="idx"
				:class="['time-tab', activeTimeTab === idx ? 'active' : '']" @click="switchTimeTab(idx)">
				{{ time }}
			</view>
		</view>

		<view class="duty-section">
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" :class="['tab', activeTab === index ? 'active' : '']"
					@click="switchTab(index)">
					{{ tab.name }}（{{ tab.selected }}）
				</view>
			</view>

			<swiper :current="activeTab" @change="onSwiperChange" :style="{ height: swiperHeight + 'px' }">
				<swiper-item>
					<scroll-view scroll-y style="max-height: 400rpx; overflow-y: auto;">
						<view class="staff-grid">
							<button v-for="staff in currentLeaders" :key="staff.id"
								:class="['staff-btn', staff.selected ? 'selected' : '']" :title="staff.name"
								@click="toggleSelection(staff)">
								{{ staff.name }}
							</button>
						</view>
					</scroll-view>
				</swiper-item>

				<swiper-item>
					<scroll-view scroll-y style="max-height: 400rpx; overflow-y: auto;">
						<view class="staff-grid">
							<button v-for="staff in currentStaff" :key="staff.id"
								:class="['staff-btn', staff.selected ? 'selected' : '']" :title="staff.name"
								@click="toggleSelection(staff)">
								{{ staff.name }}
							</button>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>

		<view class="footer">
			<uni-fab ref="fab" :pattern="pattern" horizontal="left" vertical="bottom" @fabClick="handleSubmit" />
			<uni-fab ref="fab2" :pattern="pattern2" horizontal="right" vertical="bottom" @fabClick="goToAddPeople" />
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pattern: {
					icon: "checkmarkempty"
				},
				pattern2: {
					icon: "personadd"
				},
				loading: false,
				activeTab: 0,
				activeTimeTab: 0,
				swiperHeight: 300,
				currentDate: '',
				scheduleData: {},
				leaders: [], // 带班领导
				staffs: [], // 值班人员
				// [新增] 用于跟踪被修改过的日期
				modifiedDates: new Set(),
				tabs: [{
						name: '带班领导',
						type: 'leaders',
						selected: 0,
						total: 0
					},
					{
						name: '值班人员',
						type: 'staffs',
						selected: 0,
						total: 0
					}
				],
				timeTabs: ['上午', '下午']
			};
		},
		computed: {
			currentLeaders() {
				return this.getCurrentStaff('leaders');
			},
			currentStaff() {
				return this.getCurrentStaff('staffs');
			},
			selectedDates() {
				return Object.keys(this.scheduleData)
					.filter(date => {
						const data = this.scheduleData[date];
						return (
							data?.leaders?.morning.some(l => l.selected) ||
							data?.leaders?.afternoon.some(l => l.selected) ||
							data?.staffs?.morning.some(s => s.selected) ||
							data?.staffs?.afternoon.some(s => s.selected)
						);
					})
					.map(date => ({
						date: date,
						info: '值班'
					}));
			}
		},
		watch: {
			currentDate(newDate) {
				this.updateTabStats();
			},
			activeTimeTab() {
				this.updateTabStats();
			}
		},
		created() {
			this.init();
		},
		mounted() {
			this.calculateSwiperHeight();
		},
		methods: {
			async init() {
				await this.loadPeopleData();
				this.initData();
			},
			initData() {
				const today = this.getDateString(new Date());
				this.currentDate = today;

				if (!this.scheduleData[today]) {
					this.$set(this.scheduleData, today, {
						leaders: {
							morning: this.cloneArray(this.leaders),
							afternoon: this.cloneArray(this.leaders)
						},
						staffs: {
							morning: this.cloneArray(this.staffs),
							afternoon: this.cloneArray(this.staffs)
						}
					});
				}

				this.loadDutyData(today);
			},
			async loadPeopleData() {
				try {
					const obj = uniCloud.importObject('duty-people');
					// 假设 duty-people 云对象有一个 getAllDutyPeople 方法
					const res = await obj.getDutyPeople();

					if (res.code === 0) {
						this.leaders = res.data.filter(p => p.role === 'leaders').map(p => ({
							id: p.userId,
							name: p.username,
							type: p.role,
							selected: false
						}));
						this.staffs = res.data.filter(p => p.role === 'staffs').map(p => ({
							id: p.userId,
							name: p.username,
							type: p.role,
							selected: false
						}));

						this.tabs[0].total = this.leaders.length;
						this.tabs[1].total = this.staffs.length;
					} else {
						uni.showToast({
							title: '人员数据加载失败',
							icon: 'none'
						});
					}
				} catch (e) {
					//console.error('加载人员出错:', e);
				}
			},
			async loadDutyData(selectedDate) {
				const [year, month] = selectedDate.split('-');
				const startDate = `${year}-${month}-01`;
				const endDate = `${year}-${month}-${new Date(year, month, 0).getDate()}`;

				this.loading = true;
				try {
					const obj = uniCloud.importObject('duty');
					const res = await obj.getDuty({
						startDate,
						endDate
					});

					if (res.code === 0) {
						// 将获取的数据合并到 scheduleData 中
						res.data.forEach(item => {
							const date = item.date;
							// 为保证响应性，需要确保每个员工在列表中都有记录
							const merge = (all, scheduled) => {
								return all.map(p => {
									const found = scheduled.find(s => s.id === p.id);
									return {
										...p,
										selected: !!found
									};
								});
							};

							this.$set(this.scheduleData, date, {
								leaders: {
									morning: merge(this.leaders, item.leaders?.morning || []),
									afternoon: merge(this.leaders, item.leaders?.afternoon || [])
								},
								staffs: {
									morning: merge(this.staffs, item.staffs?.morning || []),
									afternoon: merge(this.staffs, item.staffs?.afternoon || [])
								}
							});
						});

						// 为本月没有数据的日期填充默认空结构
						for (let i = 1; i <= new Date(year, month, 0).getDate(); i++) {
							const date = `${year}-${month}-${String(i).padStart(2, '0')}`;
							if (!this.scheduleData[date]) {
								this.$set(this.scheduleData, date, {
									leaders: {
										morning: this.cloneArray(this.leaders),
										afternoon: this.cloneArray(this.leaders)
									},
									staffs: {
										morning: this.cloneArray(this.staffs),
										afternoon: this.cloneArray(this.staffs)
									}
								});
							}
						}
					} else {
						uni.showToast({
							title: '数据加载失败',
							icon: 'none'
						});
					}
				} catch (e) {
					//console.error('加载出错:', e);
				} finally {
					this.loading = false;
					this.updateTabStats();
				}
			},
			getCurrentStaff(type) {
				const timeKey = this.activeTimeTab === 0 ? 'morning' : 'afternoon';
				return this.scheduleData[this.currentDate]?.[type]?.[timeKey] || this.cloneArray(this[type]);
			},
			handleMonthSwitch(e) {
				const selectedDateStr = `${e.year}-${String(e.month).padStart(2, '0')}-01`;
				this.loadDutyData(selectedDateStr);
			},
			handleDateChange(e) {
				this.currentDate = e.fulldate;
			},
			toggleSelection(staff) {
				const staffType = staff.type;
				const timeKey = this.activeTimeTab === 0 ? 'morning' : 'afternoon';
				const staffList = this.scheduleData[this.currentDate][staffType][timeKey];
				const targetStaff = staffList.find(item => item.id === staff.id);

				if (targetStaff) {
					targetStaff.selected = !targetStaff.selected;
					// [核心修改] 记录当前日期已被修改
					this.modifiedDates.add(this.currentDate);
					this.updateTabStats();
				}
			},
			updateTabStats() {
				const date = this.currentDate;
				const timeKey = this.activeTimeTab === 0 ? 'morning' : 'afternoon';
				const data = this.scheduleData[date];
				if (!data) return;

				this.tabs[0].selected = data.leaders?.[timeKey]?.filter(item => item.selected).length || 0;
				this.tabs[1].selected = data.staffs?.[timeKey]?.filter(item => item.selected).length || 0;
			},
			// [核心修改] 重写提交逻辑
			async handleSubmit() {
				if (this.modifiedDates.size === 0) {
					uni.showToast({
						title: '没有需要提交的修改',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '提交确认',
					content: `确定提交 ${this.modifiedDates.size} 天的排班变更？`,
					success: async (res) => {
						if (res.confirm) {
							this.loading = true;
							try {
								// 根据 modifiedDates 构建要提交的增量数据
								const submitData = Array.from(this.modifiedDates).map(date => {
									const dayData = this.scheduleData[date];
									return {
										date,
										leaders: {
											morning: dayData.leaders.morning.filter(l => l
												.selected),
											afternoon: dayData.leaders.afternoon.filter(l => l
												.selected)
										},
										staffs: {
											morning: dayData.staffs.morning.filter(s => s
												.selected),
											afternoon: dayData.staffs.afternoon.filter(s => s
												.selected)
										}
									};
								});

								const obj = uniCloud.importObject('duty');
								const result = await obj.updateDuty({
									data: submitData
								});

								if (result.code === 0) {
									uni.showToast({
										title: '提交成功',
										icon: 'success'
									});
									// 提交成功后，清空修改记录
									this.modifiedDates.clear();
								} else {
									uni.showToast({
										title: result.errMsg || '提交失败',
										icon: 'none'
									});
								}
							} catch (e) {
								//console.error('提交错误:', e);
								uni.showToast({
									title: '网络错误',
									icon: 'none'
								});
							} finally {
								this.loading = false;
							}
						}
					}
				});
			},
			getDateString(date) {
				const y = date.getFullYear();
				const m = String(date.getMonth() + 1).padStart(2, '0');
				const d = String(date.getDate()).padStart(2, '0');
				return `${y}-${m}-${d}`;
			},
			switchTab(index) {
				this.activeTab = index;
			},
			onSwiperChange(e) {
				this.activeTab = e.detail.current;
			},
			switchTimeTab(index) {
				this.activeTimeTab = index;
			},
			calculateSwiperHeight() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.duty-section').boundingClientRect(res => {
					if (res && res.height) {
						this.swiperHeight = res.height - 50;
					} else {
						this.swiperHeight = 300;
					}
				}).exec();
			},
			cloneArray(arr) {
				if (!Array.isArray(arr)) return [];
				return JSON.parse(JSON.stringify(arr));
			},
			goToAddPeople() {
				uni.navigateTo({
					url: '/pagesA/duty/duty-people'
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}

	.time-tabs {
		display: flex;
		margin-top: 20rpx;
		border-bottom: 2rpx solid #eee;
		background-color: #fff;
		z-index: 10;
	}

	.time-tab {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			color: #007AFF;
			font-weight: 500;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 4rpx;
				background-color: #007AFF;
			}
		}
	}

	.duty-section {
		flex: 1;
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.tabs {
		display: flex;
		border-bottom: 2rpx solid #eee;
		background-color: #fff;
		position: relative;
		z-index: 10;
	}

	.tab {
		flex: 1;
		text-align: center;
		padding: 24rpx 0;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			color: #007AFF;
			font-weight: 500;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 4rpx;
				background-color: #007AFF;
			}
		}
	}

	.staff-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(140rpx, 1fr));
		gap: 20rpx;
		padding: 20rpx;
		margin-bottom: 300rpx;
	}

	.staff-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		margin: 0;
		padding: 0;
		border-radius: 12rpx;
		background-color: #f5f5f5;
		color: #333;
		font-size: 24rpx;
		transition: all 0.2s;
		border: none;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;

		&::after {
			border: none;
		}

		&.selected {
			background-color: #007AFF;
			color: #fff;
			transform: scale(0.98);
		}
	}

	.footer {
		padding: 30rpx;
		background: #fff;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
	}
</style>